<script setup>
import { ref } from 'vue'
import { itemStockRecordPageQueryService } from '@/api/item.js'
import { Search, Refresh, DCaret, CaretTop, CaretBottom } from '@element-plus/icons-vue'
import ItemStockEdit from './components/ItemStockEdit.vue'
import { useUserStore } from '@/stores'

// 获取用户角色
const userStore = useUserStore()
const userRole = userStore.user.role

const itemStockRecordList = ref([]) // 物品库存记录列表
const total = ref(0) // 总条数
const loading = ref(false) // loading状态

// 请求参数
const params = ref({
  pageNum: 1, // 当前页码
  pageSize: 10, // 每页条数
  orderBy: 'update_time', // 排序字段
  isAsc: false, // 是否升序
  itemName: null, // 物品名称
  operationType: null, // 操作类型
  note: null // 备注
})

// 基于params参数，获取物品库存记录列表
const getItemStockRecordList = async () => {
  loading.value = true
  const res = await itemStockRecordPageQueryService(params.value)
  itemStockRecordList.value = res.data.data.list
  total.value = res.data.data.total
  loading.value = false
}
getItemStockRecordList()

// 处理分页逻辑
const onPageSizeChange = (size) => {
  params.value.pageNum = 1
  params.value.pageSize = size
  getItemStockRecordList()
}
const onPageNumChange = (page) => {
  params.value.pageNum = page
  getItemStockRecordList()
}

// 处理排序逻辑
const handleSort = (field) => {
  if (params.value.isAsc === false && params.value.orderBy === field) {
    // 如果当前已经降序，则重置排序
    params.value.orderBy = null
    params.value.isAsc = null
  } else if (params.value.orderBy === field) {
    // 如果当前已经是按该字段排序，则切换升序/降序
    params.value.isAsc = !params.value.isAsc
  } else {
    // 如果是第一次点击该字段，则默认升序
    params.value.orderBy = field
    params.value.isAsc = true
  }
  // 重新获取数据
  getItemStockRecordList()
}

// 获取排序图标
const getSortIcon = (field) => {
  if (params.value.orderBy === field) {
    return params.value.isAsc ? CaretTop : CaretBottom
  }
  return DCaret
}

// 搜索逻辑
const handleSearch = () => {
  params.value.pageNum = 1
  getItemStockRecordList()
}

// 重置逻辑
const handleReset = () => {
  params.value = {
    ...params.value, // 保留其他属性
    pageNum: 1,
    itemName: null,
    operationType: null,
    note: null
  }
  getItemStockRecordList()
}

const itemStockRecordEditRef = ref()
// 入库逻辑
const handleAdd = () => {
  itemStockRecordEditRef.value.open('入库')
}

// 出库逻辑
const handleReduce = () => {
  itemStockRecordEditRef.value.open('出库')
}

// 显示物品信息
const activeItemId = ref() // 当前需要显示的物品ID
const showItemInfoForm = (itemId) => {
  activeItemId.value = itemId
}

// 显示操作人信息
const activeOperatorUserId = ref() // 当前需要显示的操作人用户ID
const showUserInfoForm = (userId) => {
  activeOperatorUserId.value = userId
}
</script>

<template>
  <page-container title="物品库存管理">
    <template #extra>
      <el-button
        v-if="['管理员', '店长', '采购员'].includes(userRole)"
        type="primary"
        plain
        @click="handleAdd"
        >物品入库</el-button
      >
      <el-button
        v-if="['管理员', '店长', '采购员'].includes(userRole)"
        type="danger"
        plain
        @click="handleReduce"
        >物品出库</el-button
      >
    </template>
    <!-- 表单 -->
    <el-form inline>
      <el-form-item label="物品名称:"
        ><el-input v-model="params.itemName" placeholder="请输入"
      /></el-form-item>
      <el-form-item label="操作类型:">
        <el-select v-model="params.operationType" style="width: 100px">
          <el-option label="出库" value="出库"></el-option>
          <el-option label="入库" value="入库"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注:"
        ><el-input v-model="params.note" placeholder="请输入"
      /></el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleSearch"></el-button>
        <el-button type="default" :icon="Refresh" @click="handleReset"></el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table
      class="tb"
      :data="itemStockRecordList"
      v-loading="loading"
      :row-style="{ height: '50px' }"
    >
      <el-table-column prop="id" label="库存记录ID" width="120">
        <template #header>
          <span>库存记录ID</span>
          <el-icon @click="handleSort('id')">
            <component :is="getSortIcon('id')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="itemName" label="物品名称" width="150">
        <template #default="{ row }">
          <el-popover effect="light" trigger="click" placement="right" :width="600">
            <template #reference>
              <el-tag @click="showItemInfoForm(row.itemId)">{{ row.itemName }}</el-tag>
            </template>
            <ItemInfoForm v-if="activeItemId === row.itemId" :itemId="row.itemId" />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="itemName" label="操作类型" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.operationType === '入库'" type="success">入库</el-tag>
          <el-tag v-else type="danger">出库</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="数量" width="120">
        <template #default="{ row }">
          <el-tag type="info">{{ row.quantity }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="note" label="备注" width="300" show-overflow-tooltip />
      <el-table-column prop="operatorUserId" label="操作用户ID" width="120">
        <template #default="{ row }">
          <el-popover
            effect="light"
            trigger="click"
            placement="right"
            :width="600"
            :disabled="row.operatorUserId === -1"
          >
            <template #reference>
              <el-tag type="info" v-if="row.operatorUserId === -1">自动处理</el-tag>
              <el-tag v-else @click="showUserInfoForm(row.operatorUserId)">{{
                row.operatorUserId
              }}</el-tag>
            </template>
            <UserInfoForm
              v-if="activeOperatorUserId === row.operatorUserId"
              :userId="row.operatorUserId"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #header>
          <span>创建时间</span>
          <el-icon @click="handleSort('create_time')">
            <component :is="getSortIcon('create_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #header>
          <span>更新时间</span>
          <el-icon @click="handleSort('update_time')">
            <component :is="getSortIcon('update_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <!-- 空数据提示 -->
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.pageNum"
      v-model:page-size="params.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="onPageSizeChange"
      @current-change="onPageNumChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </page-container>
  <!-- 弹层 -->
  <item-stock-edit ref="itemStockRecordEditRef" @success="handleReset"></item-stock-edit>
</template>

<style lang="scss" scoped>
.tb {
  border-radius: 10px;
  box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}
</style>
